/*
 * Copyright © 2020-2021 尛飛俠（Denvie） All rights reserved.
 */

package cn.denvie.springboot.druid.component;

import cn.denvie.springboot.druid.utils.MyEncryptUtils;
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.stereotype.Component;

/**
 * DruidDataSourceEncryptBeanPostProcessor。
 *
 * @author Denvie
 * @date 2021/7/7
 * @since 1.0.0
 */
@Component
public class DruidDataSourceEncryptBeanPostProcessor implements BeanPostProcessor {
    @Autowired
    private DataSourceProperties dataSourceProperties;
    @Value("${spring.datasource.druid.encrypt.enabled:false}")
    private boolean enabled;
    @Value("${spring.datasource.druid.encrypt.secretKey}")
    private String secretKey;

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        if (bean instanceof DruidDataSource && enabled) {
            DruidDataSource druidDataSource = (DruidDataSource) bean;
            String username = dataSourceProperties.getUsername();
            druidDataSource.setUsername(MyEncryptUtils.decrypt(secretKey, username));
            String password = dataSourceProperties.getPassword();
            druidDataSource.setPassword(MyEncryptUtils.decrypt(secretKey, password));
        }
        return bean;
    }
}
